<?php
function add_trailing_slash($str = '') {
	if (empty($str) || preg_match('|/$|', $str)) return $str;
	else return $str.'/';
}

function bad_agent($agent = '') {
	return preg_match('/(Indy|Blaiz|Java|libwww-perl|Python|OutfoxBot|User-Agent|PycURL|AlphaServer|DigExt|Jakarta|Missigua|psycheclone|LinkWalker|ZyBorg|Waterunicorn|ICS)/i', $agent);
}

function bool2word($bool = true) {
	return ((bool)$bool === true) ? 'yes' : 'no';
}

function contains_spam($str = '') {
	return preg_match('/(content-type|bcc:|cc:|document.cookie|onclick|onload|javascript|alert|beastial|bestial|blowjob|clit|cock|cum|cunilingus|cunillingus|cunnilingus|cunt|ejaculate|fag|felatio|fellatio|fuck|fuk|fuks|gangbang|gangbanged|gangbangs|horny|hotsex|jism|jiz|kock|kondum|kum|kunilingus|orgasim|orgasims|orgasm|orgasms|phonesex|phuk|phuq|porn|pussies|pussy|spunk|xxx|viagra|phentermine|tramadol|adipex|advai|alprazolam|ambien|ambian|amoxicillin|antivert|blackjack|backgammon|texas|holdem|poker|carisoprodol|ciara|ciprofloxacin|debt|dating|porn)/i', $str);
}

function currentuser() {
	if (!is_logged_in()) return false;
	
	static $user;
	if (empty($user)) {
		global $tablePrefix;
		
		$cookie = get_global($_COOKIE, $tablePrefix.'loggedIn');
		$explode = explode('_', $cookie);
		$user = get_single_item(array(
			'table' => USERS,
			'class' => 'user',
			'where' => '`user_username` = "'.$explode['0'].'"'
		));
	}
	
	return $user;
}


function error($error = '', $files = true) {
	set_page_info('title', 'Error!');
	
	if ($files === true) get_header();
	echo '<h2>Error!</h2>'."\n".'<p class="error">'.$error.' <a href="javascript:history.back();">Go back.</a></p>'."\n\n";
	if ($files === true) get_footer();
}

function get_date($format = '', $date = '', $mysql = false) {
	global $dateFormats;
	
	return date((!empty($format)) ? $format : $dateFormats['standard'], (!empty($date)) ? (($mysql) ? strtotime($date) + (60 * 60 * (int)get_option('timeoffset')) : $date) : time());
}

function seo_meta()
{
	
	preg_match("/([^\/]+)\/(.+)/", $_SERVER['REQUEST_URI'], $thisslug);
	$pageslug = str_replace("/", "",$thisslug[1]);
	
	if($pageslug == "p")
	{
			$sql_select_query = "SELECT titletag, metatag FROM aa_pages where page_title_slug = '$thisslug[1]' LIMIT 0 , 1";
	   		$mysql_result = mysql_query($sql_select_query);
	   		while($datarow = mysql_fetch_array($mysql_result))
	   		{
		   		$meta_title = $datarow['titletag'];
				$meta_des = $datarow['metatag'];
	   		}
	}
	if($pageslug == "category")
	{
		$currentpage = "category";
	}
	
	$metadata = array($meta_title, $meta_des);
	return $metadata;
}

function showmeta($pagetype,$pageslug)
{
	global $metakey;
	
	if($pagetype == "p")
	{
			$sql_select_query = "SELECT metatag FROM aa_pages where page_title_slug = '$pageslug' LIMIT 0 , 1";
	   		$mysql_result = mysql_query($sql_select_query);
	   		while($datarow = mysql_fetch_array($mysql_result))
	   		{
				$metakey = $datarow['metatag'];
	   		}
	}
	if($pagetype == "category")
	{
		if($pageslug == "news")
		{
			$metakey = "Get the latest news about how to work with the MADSEN Astera clinical audiometer – the leader in hearing assessment in the US.";
		}
		if($pageslug == "tips-tricks")
		{
			$metakey = "Get tips and tricks about how to work with the MADSEN Astera clinical audiometer. The leader in hearing assessment in the US.";
		}
	}
	if($pagetype == "entry")
	{
		 	$sql_select_entry = "SELECT post_metatag FROM aa_posts where post_title_slug = '$pageslug' LIMIT 0 , 1";
	   		$mysql_result_entry = mysql_query($sql_select_entry);
	   		while($entryresult = mysql_fetch_array($mysql_result_entry))
	   		{
				$metakey = $entryresult['post_metatag'];
	   		}
	}
	return $metakey;
}

function showtitle($pagetype,$pageslug)
{
	global $title;
	
	if($pagetype == "p")
	{
			$sql_select_query = "SELECT titletag FROM aa_pages where page_title_slug = '$pageslug' LIMIT 0 , 1";
	   		$mysql_result = mysql_query($sql_select_query);
	   		while($datarow = mysql_fetch_array($mysql_result))
	   		{
				$title = $datarow['titletag'];
	   		}
	}
	if($pagetype == "category")
	{
		if($pageslug == "news")
		{
			$title = "Clinical audiometer – MADSEN Astera – news";
		}
		if($pageslug == "tips-tricks")
		{
			$title = "Clinical audiometer – MADSEN Astera – tips";
		}
	}
	if($pagetype == "entry")
	{
		 	$sql_select_entry = "SELECT post_titletag FROM aa_posts where post_title_slug = '$pageslug' LIMIT 0 , 1";
	   		$mysql_result_entry = mysql_query($sql_select_entry);
	   		while($entryresult = mysql_fetch_array($mysql_result_entry))
	   		{
				$title = $entryresult['post_titletag'];
	   		}
	}
	
	return $title;
	
}

function get_footer() {
	if (is_admin()) include(ABSPATH.'admin/footer.php');
	else include_theme_file('footer.php');
	exit;
}

function get_gravatar($email = '', $size = 40) {
	if ($email == '') return;
	return 'http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).'&amp;default=identicon&amp;size='.$size; 
}

function get_header() {
	global $pageInfo, $install;
	
	if (is_admin()) include(ABSPATH.'admin/header.php');
	else include_theme_file('header.php');
}

function get_page_meta($pageslug)
{
	
}

function get_ids($object = false) {
	$ids = array();
	
	if (!empty($object) && is_object($object)) {
		$ids = array();
		foreach($object->items as $item) {
			if (method_exists($item, 'get_id')) $ids[] = $item->get_id();
		}
	}
	
	return $ids;
}

function get_page_info($key = '') {
	global $pageInfo;
	
	if (array_key_exists($key, $pageInfo)) return $pageInfo[$key];
	else return false;
}

function get_post_data($html = false) {
	$c = array();
	if (!empty($_POST) && is_array($_POST)) foreach($_POST as $key => $value) $c[$key] = clean($value, $html);
	
	return $c;
}

function get_news_to_show($slug = ""){
	   global $news_id;
	   
	   $sql_select_query = "select news from aa_pages where page_title_slug = '$slug' LIMIT 0, 1";
	   $mysql_result = mysql_query($sql_select_query);
	   while($datarow = mysql_fetch_array($mysql_result))
	   {
		   $news_id = $datarow['news'];
	   }
	   
	   return $news_id;
}

function show_news($news_id = 0){
		global $thenews;
		
		if($news_id == 0)
		{
			$sql_select_query = "SELECT * FROM  aa_posts ORDER BY post_id DESC LIMIT 0 , 1";
	   		$mysql_result = mysql_query($sql_select_query);
	   		while($datarow = mysql_fetch_array($mysql_result))
	   		{
		   		$thenews = $datarow['post_content'];
	   		}
		}
		else
		$sql_select_query = "SELECT * FROM  aa_posts where post_id = '$news_id' LIMIT 0 , 1";
	   		$mysql_result = mysql_query($sql_select_query);
	   		while($datarow = mysql_fetch_array($mysql_result))
	   		{
		   		$thenews = $datarow;
	   		}
			
		return $thenews;
}



function get_rand() {
	$length = rand(7, 12);
	
	$rand = (int) ((rand() + rand() + rand()) / rand()) + rand() - (rand()/2);
	if ($rand < 0) get_rand();
	
	$rand = md5($rand);
	if (rand(0, 1)) $rand = preg_replace('/[a-z]+/', '', $rand);
	if ($length > strlen($rand)) $length = strlen($rand);
	
	return substr($rand, 0, $length);
}

function get_single_item($options = array(), $object = null) {
	if (!is_null($object)) {
		foreach($object->items as $item) {
			if (isset($item->$options['0']) && $item->$options['0'] == $options['1']) return $item;
		}
	} else {
		$items = new items(array_merge($options, array(
			'limit' => 1,
			'pagination' => false
		)));
		
		if ($items->total === 1) return $items->items['0'];
		else return false;
	}
}

function get_slug($str = '') {
	return (!empty($str)) ? trim(preg_replace('/[-]+/', '-', preg_replace('/[ ]+/', '-', trim(preg_replace('/[^a-z0-9-]/', ' ', strtolower($str)))))) : '';
}

function include_file($file = '', $vars = array()) {
	global $globals;
	
	if (empty($file)) return false;
	static $files = array();
	$vars = array_merge($globals, (array)$vars);
	
	if (count($vars) > 0) eval('global $'.implode(', $', $vars).';');
	
	if (!in_array($file, $files)) {
		include($file);
		$files[] = $file;
	}
	
	return true;
}

function is_admin() {
	return (defined('ISADMIN') && ISADMIN === true);
}

function is_logged_in() {
	global $tablePrefix;
	$cookie = get_global($_COOKIE, $tablePrefix.'loggedIn');
	$explode = explode('_', $cookie);
	
	if (!empty($cookie) && !empty($explode) && count($explode) === 2) {
		$user = get_single_item(array(
			'table' => USERS,
			'class' => 'user',
			'where' => '`user_username` = "'.escape($explode['0']).'"'
		));
		
		return (!empty($user)) ? ($cookie === $user->get_username().'_'.md5(SECRET.sha1($user->get_password().get_date('n')))) : false;
	} else return false;
}

function make_link($options = array()) {
	$link = '<a href="'.$options['href'].'"';
	if (!empty($options['title'])) $link .= ' title="'.$options['title'].'"';
	if (!empty($options['class'])) $link .= ' class="'.$options['class'].'"';
	$link .= '>'.$options['text'].'</a>';
	
	return $link;
}

function remove_leading_slash($str = '') {
	return preg_replace('#^/#', '', $str);
}

function set_page_info($key = '', $value = '') {
	global $pageInfo;
	
	return $pageInfo[$key] = $value;
}

function valid_email($email) {
	if (strpos($email, '@') !== false && strpos($email, '.') !== false) return preg_match("/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i", $email);
	else return false;
}

function valid_password($password = '') {
	return (!empty($password) && preg_match('/^[a-zA-Z0-9_-]{6,14}$/', $password));
}

function valid_slug($slug = '') {
	return (!empty($slug) && preg_match('/^[a-z0-9-]+$/', $slug));
}

function valid_url($url) {
	return preg_match('/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i', $url);
}

function valid_username($username = '') {
	return (!empty($username) && preg_match('/^[a-zA-Z0-9_-]{4,18}$/', $username));
}

function nice_array($array,$var_dump=false){echo '<pre>';if($var_dump){var_dump($array);}else{print_r($array);}echo '</pre>';}
?>